package com.briup.estore.adminAPI.web.filter;

import com.briup.estore.common.bean.Admin;
import com.briup.estore.common.exception.ShopCommonException;
import com.briup.estore.common.util.JwtUtil;
import com.briup.estore.common.util.RedisCache;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author adam
 * @date 2023/5/15
 */
@Component
@Slf4j
public class AdminFilter implements HandlerInterceptor {
    @Autowired
    RedisCache redisCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse resp, Object handler) throws Exception {
        log.info(request.getMethod() + "：" + request.getRequestURI());
        if (request.getMethod().equals("OPTIONS") || !(handler instanceof HandlerMethod)) {
            return true;    // 静态资源直接放行
        }
        String token = request.getHeader("token");
        log.info("token:{}", token);
        if (ObjectUtils.isEmpty(token)) {
            throw new ShopCommonException(51000, "用户未登录");
        }
        String userName;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userName = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShopCommonException(51000, "token非法");
        }
        //从redis中获取用户信息
        String redisKey = userName;
        String tokenForRedis = redisCache.getCacheObject(redisKey);
        if (ObjectUtils.isEmpty(tokenForRedis)) {
            throw new ShopCommonException(51000, "身份信息已经过期");
        }
//        重新计算有效期
        redisCache.expire(redisKey, JwtUtil.JWT_TTL, TimeUnit.MILLISECONDS);
        log.info(request.getMethod() + "：" + request.getRequestURI() + "该请求通过");
        return true;
    }

}




